package com.spvs.system.utils;

import com.spvs.common.core.utils.DateUtils;
import com.spvs.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.springframework.beans.factory.annotation.Value;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class PDFUtils {

    /**
     * @param oldPath 文件路径
     * @param pngPath 签名路径
     * @param outPath 新文件路径
     * @param x
     * @throws IOException
     */

    private static final int IMAGES_PER_ROW = 3;
    private static final int IMAGES_PER_PAGE = 15;

    public static String modifyPdf(String oldPath, String pngPath, String outPath, int index) {
        PDDocument document = null;
        PDPageContentStream contentStream = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(oldPath);
            String encode = URLEncoder.encode(url.toString(), StandardCharsets.UTF_8.name());
            encode = encode.replace("%2F", "/");
            encode = encode.replace("%3A", ":");
            URLConnection connection = new URL(encode).openConnection();
            connection.connect();
            inputStream = connection.getInputStream();
            document = PDDocument.load(inputStream);
//            document = loadPdfFromUrl(oldPath);

            // 如果是第一次或者达到最大图片数量，新增一页
            boolean isNewPageNeeded = (index - 1) % IMAGES_PER_PAGE == 0 || index == 1;
            if (isNewPageNeeded) {
                PDPage newPage = new PDPage(PDRectangle.A4);
                document.addPage(newPage);
                contentStream = new PDPageContentStream(document, newPage);
            }

            PDImageXObject image = PDImageXObject.createFromFile(pngPath, document);

            float imgWidth = 150f;
            float imgHeight = 80f;

            // 计算图片位置
            index -= 1;
            int pageIndex = index % IMAGES_PER_PAGE;
            float posX, posY;
            int row = pageIndex / IMAGES_PER_ROW;
            int column = pageIndex % IMAGES_PER_ROW;
            posX = column * (imgWidth + 50);
            posY = PDRectangle.A4.getHeight() - (row + 1) * (imgHeight + 75) - 20;

            // 绘制图片
            if (contentStream == null) {
                PDPage currentPage = document.getPage(document.getNumberOfPages() - 1);
                contentStream = new PDPageContentStream(document, currentPage, PDPageContentStream.AppendMode.APPEND, false, false);
            }
            contentStream.drawImage(image, posX, posY, imgWidth, imgHeight);

            // 关闭流并保存文档
            contentStream.close();
            document.save(outPath);
            return outPath;
        } catch (IOException e) {
            System.err.println("Error modifying PDF: " + e.getMessage());
        } finally {
            closeQuietly(contentStream);
            closeQuietly(document);
            closeQuietly(inputStream);
        }
        return null;
    }


    private static void closeQuietly(AutoCloseable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception ignored) {
            }
        }
    }

    public static final String extractFilename(String fileName) {
        return StringUtils.format("/{}/{}", DateUtils.datePath(),
                fileName);
    }
}
